app.controller('receiveOrderCtrl', ['$scope','receiveOrderFactory','appFactory','BaseService','$stateParams','$ionicLoading','$cordovaBarcodeScanner',
    function($scope,receiveOrderFactory,appFactory,BaseService,$stateParams,$ionicLoading,$cordovaBarcodeScanner) {

        $scope.rush = function(event,o,index){
            //更新订单状态，并且移除调该订单
            event = event ? event : window.event;
            var obj = event.srcElement ? event.srcElement : event.target;
            obj.disabled=true;

            $scope.canRush = 0;
            if(o.get('messioned')===true){
                return;
            };
            //return;
            receiveOrderFactory.rushMession(o).then(function(res){
                o.set('messioned',true);
                alert('抢单成功!快快出发把~');
            }).catch(function(err){
                alert(err.error);
                $scope.canRush = 1;
            });
        }

     $scope.getOrdersArray = function(){
         var uid = appFactory.getUserInfo().uid;
         var areaId = appFactory.getUserInfo().user.area;
         var Order = AV.Object.extend("Order");
         var PAGE_SIZE = 20;
         async.waterfall([
             function(callback){

                 var ORDER_STATUS = [2500,3000,4000];
                 var orderQuery0 = new AV.Query(Order);
                 orderQuery0.containedIn('status',ORDER_STATUS);
                 orderQuery0.equalTo("syncStatus",0);
                 orderQuery0.notEqualTo('messioned',true);
                 orderQuery0.limit(PAGE_SIZE);
                 orderQuery0.equalTo("type",6);
                 orderQuery0.containedIn("areaId",areaId);
                 orderQuery0.addDescending("bookdate");
                 orderQuery0.addDescending("paytime");

                 var orderQuery1 = new AV.Query(Order);
                 orderQuery1.containedIn('status',ORDER_STATUS);
                 orderQuery1.equalTo("syncStatus",0);
                 orderQuery1.notEqualTo('messioned',true);
                 orderQuery1.notContainedIn('type',[11,12]);
                 orderQuery1.limit(PAGE_SIZE);
                 orderQuery1.containedIn("areaId",areaId);
                 orderQuery1.addDescending("bookdate");
                 orderQuery1.addDescending("paytime");

                 var orderQuery2 = new AV.Query(Order);

                 orderQuery2.containedIn('status',ORDER_STATUS);
                 orderQuery2.equalTo("syncStatus",0);
                 orderQuery2.notEqualTo('messioned',true);
                 orderQuery2.limit(PAGE_SIZE);
                 orderQuery2.equalTo("type",9);
                 orderQuery2.addDescending("bookdate");
                 orderQuery2.addDescending("paytime");

                 var query = AV.Query.or(orderQuery0,orderQuery1,orderQuery2);

                 query.find().then(function(res){
                     $scope.$apply(function(){
                         $scope.ordersArray = res;
                         callback(null,$scope.ordersArray);
                     });
                 }).catch(function(err){
                     console.log(err);
                     callback(err);
                 }).finally(function(){
                     $scope.$broadcast('scroll.refreshComplete');
                 });
             },
             function(orders,callback){
                 var orderQuery = new AV.Query(Order);
                 var ORDER_STATUS = [2500,3000,4000];
                 orderQuery.containedIn('status',ORDER_STATUS);
                 orderQuery.equalTo("syncStatus",0);
                 orderQuery.containedIn("areaId",areaId);
                 orderQuery.count({
                     success: function(count) {
                         $scope.ordersCount = count;
                     },
                     error: function(error) {
                         $scope.ordersCount = 0;
                     }
                 });

                 callback(null,orders);
             },
             function(orders,callback){
                 var orderQuery = new AV.Query(Order);
                 var ORDER_STATUS = [2500,3000,4000];
                 orderQuery.containedIn('status',ORDER_STATUS);
                 orderQuery.equalTo("syncStatus",0);
                 orderQuery.containedIn("areaId",areaId);
                 orderQuery.notEqualTo('messioned',true);
                 orderQuery.count({
                     success: function(count) {
                         $scope.rOrdersCount = count;
                     },
                     error: function(error) {
                         $scope.rOrdersCount = 0;
                     }
                 });

                 callback(null);
             },
         ],function(err,result){
            if(err){
                console.log(err);
            }else{
                console.log("OK");
            }
         });
     }
     $scope.getOrdersArray();



    $scope.barscanReceive = function(){
        $cordovaBarcodeScanner
            .scan()
            .then(function(barcodeData) {
                //alert(JSON.stringify(barcodeData));
                var cancelled = barcodeData.cancelled;
                var result = JSON.parse(barcodeData.text);
                //alert('cancelled:'+cancelled);
                //alert('result:'+result);
                if(!cancelled){
                    var oid = result.OID;
                    var storage = window.localStorage;
                    var uid = storage.getItem("uid");
                    if (oid){
                        var Order = AV.Object.extend("Order");
                        var orderQuery = new AV.Query(Order);
                        orderQuery.equalTo('orderid',oid);
                        orderQuery.first().then(function(res){
                            // 若打包时间比较当前时间超过一小时则不可扫码领取
                            var status = res.get('status');
                            if(status === 4000){
                                var oneday = 1000 * 60 * 60 * 7;
                                var oneday2 = 1000 * 60 * 60 * 8;
                                var oneday3 = 1000 * 60 * 60 * 9;
                                var today = new Date();
                                today.setHours(0);
                                today.setMinutes(0);
                                today.setSeconds(0);
                                today.setMilliseconds(0);
                                today = Date.parse(today);

                                var yesterday = Date.parse(new Date(today - oneday));
                                var jintiane = Date.parse(new Date(today + oneday2));
                                var jintiann = Date.parse(new Date(today + oneday3));
                                var timestamp = Date.parse(new Date());
                                var warehouseendtime = res.get('warehouseendtime').getTime();

                                if ((warehouseendtime > yesterday && warehouseendtime < jintiane)&&(timestamp<jintiann)){
                                    BaseService.barscanHandle(uid,oid).then(function(res){
                                        //alert(res.msg);
                                        var r=confirm(res.msg+"\r\n是否继续扫码!");
                                        if (r==true) {
                                            $scope.barscanReceive();
                                        }
                                    }).catch(function(err){
                                        //alert(err.msg);
                                        var r=confirm(res.msg+"\r\n是否继续扫码!");
                                        if (r==true) {
                                            $scope.barscanReceive();
                                        }
                                    });
                                }else{
                                    var minute = 1000 * 60;
                                    var hour = minute * 60;
                                    var twohour = hour * 2;
                                    var time = timestamp - warehouseendtime;
                                    if (time>twohour) {
                                        var r = confirm("此订单领取时间已超时,不能扫码!昨日打包完成的订单9点前领取,今日打包完成的订单2小时内领取,\r\n是否继续扫码!");
                                        if (r == true) {
                                            $scope.barscanReceive();
                                        }
                                    }else{
                                        BaseService.barscanHandle(uid,oid).then(function(res){
                                            //alert(res.msg);
                                            var r=confirm(res.msg+"\r\n是否继续扫码!");
                                            if (r==true) {
                                                $scope.barscanReceive();
                                            }
                                        }).catch(function(err){
                                            //alert(err.msg);
                                            var r=confirm(res.msg+"\r\n是否继续扫码!");
                                            if (r==true) {
                                                $scope.barscanReceive();
                                            }
                                        });
                                    }
                                }
                            }else{
                                BaseService.barscanHandle(uid,oid).then(function(res){
                                    //alert(res.msg);
                                    var r=confirm(res.msg+"\r\n是否继续扫码!");
                                    if (r==true) {
                                        $scope.barscanReceive();
                                    }
                                }).catch(function(err){
                                    //alert(err.msg);
                                    var r=confirm(res.msg+"\r\n是否继续扫码!");
                                    if (r==true) {
                                        $scope.barscanReceive();
                                    }
                                });
                            }
                        }).catch(function(err){
                            alert(err);
                            var r=confirm("没有扫描到正确的订单信息!\r\n是否继续扫码!");
                            if (r==true) {
                                $scope.barscanReceive();
                            }
                        });
                    }else{
                        var r=confirm("没有扫描到正确的订单ID信息!\r\n是否继续扫码!");
                        if (r==true) {
                            $scope.barscanReceive();
                        }
                    }
                }else{
                    alert('扫描异常或退出扫描');
                }
            }, function(error) {
                // An error occurred
            });
    }
}]);
